package com.googlecode.garbagecan.commons.clistudy.ftp;

import org.apache.commons.cli.BasicParser;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;

public class CommandParser {
	private Options options;
	private Option optHelp;
	private Option optVersion;
	private Option optGet;
	private Option optPut;
	
	public CommandParser() {
		optHelp = new Option("h", false, "print this help and exit");
		optVersion = new Option("v", false, "print version information and exit");

		optGet = new Option("get", true, "get <remote_file> to <local_file>");
		optGet.setArgs(2);
		optGet.setArgName("remote_file> <local_file");
		
		optPut = new Option("put", true, "put <local_file> to <remote_file>");
		optPut.setArgs(2);
		optPut.setArgName("local_file> <remote_file");
		
		options = new Options();
		options.addOption(optHelp);
		options.addOption(optVersion);
		options.addOption(optGet);
		options.addOption(optPut);
	}

	public Command parse(String[] args) {
		CommandLineParser parser = new BasicParser();
		CommandLine cl = null;
		Command cmd;

		try {
			cl = parser.parse(options, args);
		} catch (ParseException ex) {
			ex.printStackTrace();
			return new HelpCommand();
		}
		
		Option[] opts = cl.getOptions();
		if (opts == null) {
			cmd = new HelpCommand();
		} else if (cl.hasOption(optHelp.getOpt())) {
			cmd = new HelpCommand();
		} else if (cl.hasOption(optVersion.getOpt())) {
			cmd = new VersionCommand();
		} else if (cl.hasOption(optGet.getOpt())) {
			String[] values = cl.getOptionValues(optGet.getOpt());
			int length = values.length;
			if (length == 2) {
				cmd = new GetCommand(values[0], values[1]);
			} else {
				cmd = new HelpCommand();
			}
		} else if (cl.hasOption(optPut.getOpt())) {
			String[] values = cl.getOptionValues(optPut.getOpt());
			int length = values.length;
			if (length == 2) {
				cmd = new PutCommand(values[0], values[1]);
			} else {
				cmd = new HelpCommand();
			}
		} else {
			cmd = new HelpCommand();
		}
		return cmd;
	}
	
	public Options getOptions() {
		return this.options;
	}
}
